<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名称" v-model="listQuery.title">
      </el-input>

      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="用户组">
        <el-option v-for="item in  groupOptions" :key="item.id" :label="item.title" :value="item.id">
        </el-option>
      </el-select>

      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.status" placeholder="状态">
        <el-option v-for="item in  statusOptions" :key="item.key" :label="item.label" :value="item.code">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="所属用户组">
        <template slot-scope="scope">
          <span>{{groupFilter(scope.row.group_id)}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="姓名" >
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>

      <el-table-column width="120" align="center" label="手机" >
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="邮箱" >
        <template slot-scope="scope">
          <span>{{scope.row.email}}</span>
        </template>
      </el-table-column>

      <el-table-column width="80" class-name="status-col" label="状态" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusTagFilter">{{scope.row.status | statusTextFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status==-1" size="mini" type="warning" @click="handleDelete(scope.row)">恢复</el-button>
          <el-button v-else size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='margin-left:50px;margin-right: 50px;'>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>

        <div class="form-row">
          <el-col :span="12">
            <el-form-item label="用户组" prop="group_id">
              <el-select class="filter-item" v-model="temp.group_id" placeholder="请选择所属用户组">
                <el-option key="0" label="系统管理员" :value="0"></el-option>
                <el-option v-for="item in  groupOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </div>

        <div class="form-row">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input type="string" v-model="temp.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input type="string" v-model="temp.phone"></el-input>
            </el-form-item>
          </el-col>
        </div>

        <div class="form-row">
          <el-col :span="12">
            <el-form-item  label="密码" prop="password">
              <el-input v-model="temp.password" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重复密码" prop="repwd">
              <el-input v-model="temp.repwd" type="password"></el-input>
            </el-form-item>
          </el-col>
        </div>

        <div class="form-row">
          <el-col :span="12">
            <el-form-item  label="邮箱" prop="email">
              <el-input v-model="temp.email" type="email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select class="filter-item" v-model="temp.status" placeholder="请选择默认状态">
                <el-option v-for="item in  statusOptions" :key="item.code" :label="item.label" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { fetchList, createUser, saveUser, updateUser, deleteUser } from '@/api/user'
  import waves from '@/directive/waves' // 水波纹指令

  const statusOptions = [
    { key: 'success', label: '正常', code: 1 },
    { key: 'warning', label: '异常', code: 0 },
    { key: 'danger', label: '删除', code: -1 }
  ]
  const statusKeyValue = statusOptions.reduce((acc, cur) => {
    acc[cur.code] = { tag: cur.key, txt: cur.label }
    return acc
  }, {})

  export default {
    name: 'user',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          title: undefined,
          type: undefined,
          status: undefined
        },
        groupOptions: null,
        statusOptions,
        showReviewer: false,
        temp: {
          id: undefined,
          username: '',
          name: '',
          phone: undefined,
          email: undefined,
          group_id: 0,
          password: '',
          repwd: '',
          status: 1
        },
        dialogFormVisible: false,
        dialogStatus: '',
        dialogTitleMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
          group_id: [{ required: true, message: '用户组不能为空', trigger: 'change' }],
          password: [],
          repwd: []
        }
      }
    },
    filters: {
      statusTagFilter(status) {
        return statusKeyValue[status].tag
      },
      statusTextFilter(status) {
        return statusKeyValue[status].txt
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        const $vm = this
        this.axios.all([fetchList(), createUser()]).then(this.axios.spread(function(list, configs) {
          $vm.groupOptions = configs.group
          $vm.list = list.items
          $vm.total = list.total
          $vm.listLoading = false
        }))
      },
      groupFilter(group_id) {
        if (!group_id) return '系统管理员'
        const list = this.groupOptions
        if (list === null) return
        for (let i = 0, len = list.length; i < len; i++) {
          if (list[i].id === group_id) return list[i].name
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          username: '',
          group_id: 0,
          name: '',
          phone: undefined,
          email: undefined,
          password: '',
          repwd: '',
          status: 1
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        // 添加验证条件
        if (this.rules.password.length === 0) {
          const rule = { required: true, message: '密码不能为空', trigger: 'blur' }
          this.rules.password.push(rule)
          this.rules.repwd.push(rule)
        }
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            saveUser(this.temp).then((data) => {
              this.temp.id = data.id
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        // 移除验证条件
        if (this.rules.password.length === 1) {
          this.rules.password.splice(0, 1)
          this.rules.repwd.splice(0, 1)
        }
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateUser(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        const status = row.status === 1
        deleteUser(row.id, status).then(() => {
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          row.status = status ? -1 : 1
        })
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .form-row{
    /*display: table;*/
    position: relative;
  }
  .form-row:after {
    clear: both;
  }
  .form-row:after, .form-row:before {
    display: table;
    content: "";
  }
</style>
